package com.tungse.juc;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;


/**
 * @Author : Tungse
 * @Date: 2025/7/24 8:50
 * @Description:
 */
public class CompletableFutureTest {
    static ThreadPoolExecutor threadPool =
            new ThreadPoolExecutor(10, 10, 1, TimeUnit.SECONDS, new ArrayBlockingQueue<>(10));


    public static void main(String[] args) throws ExecutionException, InterruptedException {
//        Future<String> future = threadPool.submit(() -> "Result");
//// 同步阻塞等待
//        String result = future.get();
//        System.out.println(result);

// 非阻塞回调
//        CompletableFuture.supplyAsync(() -> "Result").thenAccept(a -> System.out.println("Callback: " + a));

        //串联任务
        CompletableFuture.supplyAsync(() -> 1001).thenApplyAsync(userId -> "User-" + userId).thenAcceptAsync(System.out::println);
        Thread.sleep(100);


        CompletableFuture<Integer> cf1 = CompletableFuture.supplyAsync(() -> 10);
        CompletableFuture<Integer> cf2 = CompletableFuture.supplyAsync(() -> 0);
//        cf1.thenCombine(cf2, Integer::sum).thenAccept(sum -> System.out.println("Sum: " + sum));
        Integer join = CompletableFuture.allOf(cf1, cf2).thenApply(v -> cf1.join() / cf2.join())
                .thenApply(sum -> {
                    System.out.println("Sum: " + sum);
                    return sum;
                })
                .exceptionally(ex->0)
                .join();

        System.out.println("最终结果" + join);
    }
}
